/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.command.account;

import apus.command.AbstractCommand;
import apus.entity.Account;
import apus.entity.Period;
import apus.exception.BusinessException;
import apus.persistence.AccountDAO;
import apus.persistence.PeriodDAO;
import apus.services.ServiceLocator;
import java.util.Arrays;
import java.util.List;

/**
 * The
 * <code>UpdateAccountCommand</code> class represents command for changing
 * information about account.
 * @author Maxim Vasilevsky
 * @author Roman Dyatkovsky
 * @since APUS v0.4
 * @see AbstractCommand
 */
public class UpdateAccountCommand extends AbstractCommand {

    private final static String PARAM_ID = "Id";
    private final static String PARAM_PERIOD_ID = "Period id";
    private final static String[] paramsNames = {PARAM_ID, PARAM_PERIOD_ID};

    public UpdateAccountCommand() {
        super("Update account");
    }

    @Override
    public void execute() {
        int ID, periodID;
        String stringId = params.get(PARAM_ID);
        String strPerId = params.get(PARAM_PERIOD_ID);
        
        try{
            ID = Integer.parseInt(stringId);
            periodID = Integer.parseInt(strPerId);
        } catch (NumberFormatException e) {
            throw new BusinessException("Wrong ID format.", e);
        }

        AccountDAO accountDAO = ServiceLocator.getService(AccountDAO.class);
        PeriodDAO periodDAO = ServiceLocator.getService(PeriodDAO.class);
        
        Account account = accountDAO.read(ID);
        Period period = periodDAO.read(periodID);
        
        if (account == null) {
            throw new BusinessException("Account not found");
        }
        
        if (period == null) {
            throw new BusinessException("Period not found");
        }
        
        account.setPeriod(period);
        account.calculate();
        accountDAO.update(account);
    }

    @Override
    public List<String> getParamNames() {
        return Arrays.asList(paramsNames);
    }
}
